#!/bin/bash
# made by dargonli , 2020-10-12
# 安装kubelet kubeadm kubectl
# kubelet.sh

[[ $UID -ne 0 ]] && { echo "Must run in root user !";exit; }

#默认版本 1.15.5
Ver=${Ver:-1.15.5}

############################

#修改docker cgroup driver为systemd
Cgroup() {
#docker check 
docker images &>/dev/null
[[ $? = 0 ]] || { echo "install docker";cat ./docker.sh |bash ; }
docker images &>/dev/null
[[ $? = 0 ]] || { echo "docker error";exit; }
#
if [ `docker info | grep "Cgroup.*systemd" |wc -l` -eq 0 ];then
sed -i 's/--registry-mirro.*aliyuncs.com//' /usr/lib/systemd/system/docker.service
mkdir -p /etc/docker/
cat>/etc/docker/daemon.json<<EOF
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "registry-mirrors": ["https://y3asdhja.mirror.aliyuncs.com"],
  "storage-driver": "overlay2",
  "storage-opts": ["overlay2.override_kernel_check=true"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m",
    "max-file": "3"
  }
}
EOF
systemctl daemon-reload
systemctl restart docker
fi
}

Install_kube(){
echo "安装kubelet kubeadm v$Ver"
if [[ -f /etc/redhat-release ]];then
#CentOS / RHEL / Fedora
[ "$Remove" = "1" ] && { yum -y remove kubelet kubeadm kubectl &>/dev/null; }
#配置源
echo '#k8s
[kubernetes]
name=Kubernetes
baseurl=https://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=0
'>/etc/yum.repos.d/kubernetes.repo
#kubeadm和相关工具
yum -y install kubelet-$Ver kubeadm-$Ver kubectl-$Ver ipvsadm ipset net-tools jq
systemctl daemon-reload
systemctl enable kubelet
exit

#Debian / Ubuntu
elif [[ -f /etc/debian_version ]];then
 if [ "$Remove" = "1" ];then
    apt remove -y kubelet kubeadm kubectl &>/dev/null
 else
    apt-get update && apt-get install -y apt-transport-https
    curl -s https://mirrors.aliyun.com/kubernetes/apt/doc/apt-key.gpg | apt-key add - 
    echo 'deb https://mirrors.aliyun.com/kubernetes/apt/ kubernetes-xenial main' >/etc/apt/sources.list.d/kubernetes.list
fi
apt-get update
apt-get install -y kubelet=$Ver-00 kubeadm=$Ver-00 kubectl=$Ver-00 ipvsadm ipset net-tools jq
bash /etc/sysconfig/modules/ipvs.modules &>/dev/null
systemctl enable kubelet
exit

else
  echo "I don't know the OS"
  exit
fi
}

############################

#base config
[ -f /etc/sysctl.d/k8s.conf -a -f /etc/sysconfig/modules/ipvs.modules ] || { cat ./k8s.set0.sh |bash ; }

#check docker and cgroup
Cgroup

#检测是否安装kubeadm
which kubeadm &>/dev/null
[ $? -eq 0 ] || { Install_kube; }

#版本不相符重新安装
[ "$(kubelet --version |awk '{print $2}')" = "v${Ver}" ] || { Remove=1;Install_kube; }
[ "$(kubeadm version -o yaml |awk '/gitVersion/{print $NF}')" = "v${Ver}" ] || { Remove=1;Install_kube; }
kubectl version --short &>/tmp/kubectl.log
[ "$(awk '/Client/{print $NF}' /tmp/kubectl.log)" = "v${Ver}" ] || { Remove=1;Install_kube; }